<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no">
    <title>Service Worker</title>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge">
    <meta http-equiv="Cache-Control" content="no-siteapp">
    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate"/>
    <meta http-equiv="Pragma" content="no-cache"/>
    <meta http-equiv="Expires" content="0"/>
    <meta name="renderer" content="webkit|ie-comp|ie-stand">
    <meta content="telephone=no" name="format-detection"/>
    <meta name="viewport"
          content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/>
    <meta name="baidu-site-verification" content="v3r4JDDzPy"/>
    <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
    <style>
        span:empty::before{
            content: '缺省值';
            color: gray;
        }
    </style>
</head>
<body>
<div id="app">
    <p><img src="./cattle.jpg" alt="实例图片" width="320" height="180"></p>
    <h3>一些提示信息</h3>
    <ul>
        <li>浏览器是否支持：<span id="isSupport"></span></li>
        <li>service worker是否注册成功：<span id="isSuccess"></span></li>
        <li>当前注册状态：<span id="state"></span></li>
        <li>当前service worker状态：<span id="swState"></span></li>
    </ul>
</div>
<script>
    if('serviceWorker' in navigator){
        $('#isSupport').text('支持');

        // 开始注册service workers
        navigator.serviceWorker.register('./sw-demo-cache.js',{scope: './'})
            .then(function (registration) {
                $('#isSuccess').text('注册成功');

                var serviceWorker;
                if(registration.installing){
                    serviceWorker = registration.installing;
                    $('#state').text('installing');
                }else if(registration.waiting){
                    serviceWorker = registration.waiting;
                    $('#state').text('waiting');
                }else if(registration.active){
                    serviceWorker = registration.action;
                    $('#state').text('active');
                }

                if(serviceWorker){
                    $('#swState').text(serviceWorker.state);
                    serviceWorker.addEventListener('statechange', function (e) {
                        $('#swState').append('&emsp;状态变化为' + e.target.state);
                    })
                }
            }).catch(function (error) {
                console.error(error);
                $('#isSuccess').text('注册没有成功');
        })
    }else {
        $('#isSuccess').text('不支持');
    }
</script>
</body>
</html>